package com.xiaoyang.ssyx.home.service.impl;

import com.xiaoyang.ssyx.activity.client.ActivityFeignClient;
import com.xiaoyang.ssyx.client.product.ProductFeignClient;
import com.xiaoyang.ssyx.client.search.SkuFeignClient;
import com.xiaoyang.ssyx.home.service.ItemService;
import com.xiaoyang.ssyx.vo.product.SkuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @AUTHOR XiaoYang
 * @DATE 2023/7/3-16:07
 * @DESCRIPTION TODO
 */
@Service
public class ItemServiceImpl implements ItemService {

    //自定义线程池
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private ActivityFeignClient activityFeignClient;

    @Autowired
    private SkuFeignClient skuFeignClient;

    /**
     * 获取sku详细信息
     *  使用异步实现 但是当三个都完成时才返回
     * @param skuId skuId
     * @param userId userId
     * @return map
     */
    @Override
    public Map<String, Object> item(Long skuId, Long userId) {
        Map<String, Object> result = new HashMap<>();

        //skuId查询
        CompletableFuture<SkuInfoVo> skuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            //远程调用获取sku对应数据(service-product)
            SkuInfoVo skuInfoVo = productFeignClient.getSkuInfoVo(skuId);
            result.put("skuInfoVo", skuInfoVo);
            return skuInfoVo;
        },threadPoolExecutor);

        //sku对应优惠券信息
        CompletableFuture<Void> activityCompletableFuture = CompletableFuture.runAsync(() -> {
            //远程调用获取优惠券(service-activity)
            Map<String ,Object> activityMap = activityFeignClient.findActivityAndCoupon(skuId,userId);
            result.putAll(activityMap);
        },threadPoolExecutor);

        //更新商品热度
        CompletableFuture<Void> hotCompletableFuture = CompletableFuture.runAsync(() -> {
            //远程调用更新热度(service-search)
            skuFeignClient.incrHotScore(skuId);
        },threadPoolExecutor);

        //都完成之后进行返回
        CompletableFuture<Void> all = CompletableFuture.allOf(
                skuInfoCompletableFuture,
                activityCompletableFuture,
                hotCompletableFuture
        );
        all.join();


        return result;
    }
}
